<?php


namespace app\worker;


use app\lib\Jwt;
use GatewayWorker\Lib\Gateway;
use think\Exception;
use think\worker\Application;
use Workerman\Worker;

class Events
{
    /**
     * onWorkerStart 事件回调
     * 当businessWorker进程启动时触发。每个进程生命周期内都只会触发一次
     *
     * @access public
     * @param  \Workerman\Worker    $businessWorker
     * @return void
     */
    public static function onWorkerStart(Worker $businessWorker)
    {
        $app = new Application;
        $app->initialize();
    }

    /**
     * onConnect 事件回调
     * 当客户端连接上gateway进程时(TCP三次握手完毕时)触发
     *
     * @access public
     * @param  int       $client_id
     * @return void
     */
    public static function onConnect($client_id)
    {

    }

    /**
     * onWebSocketConnect 事件回调
     * 当客户端连接上gateway完成websocket握手时触发
     *
     * @param  integer  $client_id 断开连接的客户端client_id
     * @param  mixed    $data
     * @return void
     */
    public static function onWebSocketConnect($client_id, $data)
    {
        try{
            //处理token
            $uid=Jwt::decode($data['get']['token']);

            Gateway::bindUid($client_id,$uid);
            Gateway::sendToClient($client_id,json_encode([
                'type'=>'connect_success',
                'data'=>[
                    'msg'=>'通信服务接入成功'
                ]
            ]));
            //默认加入群主
            list($app_id,$user_id)=explode('_',$uid);

            Gateway::joinGroup($uid,$app_id);
        }catch (Exception $exception){
            Gateway::sendToClient($client_id,json_encode([
                'type'=>'connect_fail',
                'data'=>[
                    'msg'=>$exception->getMessage()
                ]
            ]));

            //关闭连接
            Gateway::closeClient($client_id);
        }
    }

    /**
     * onMessage 事件回调
     * 当客户端发来数据(Gateway进程收到数据)后触发
     *
     * @access public
     * @param  int       $client_id
     * @param  mixed     $data
     * @return void
     */
    public static function onMessage($client_id, $data)
    {
        //处理用户之间的相互通信

        Gateway::sendToUid($data['to_uid'],json_encode($data['content']));
    }


    public static function onClose($client_id)
    {
        GateWay::sendToAll("client[$client_id] logout\n");
    }

    /**
     * onWorkerStop 事件回调
     * 当businessWorker进程退出时触发。每个进程生命周期内都只会触发一次。
     *
     * @param  \Workerman\Worker    $businessWorker
     * @return void
     */
    public static function onWorkerStop(Worker $businessWorker)
    {
        echo "WorkerStop\n";
    }
}